package com.example.demo.util;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class ImageDownloader {
    public static void main(String[] args) {
        String url = "https://cn.bing.com/search?q=%E5%B0%8F%E7%BA%A2%E4%B9%A6%E5%A4%B4%E5%83%8F&form=ANNTH1&refig=68297a8749824f91b996607cc4459587&pc=CNNDDB"; // 替换为实际网页 URL
        // 修改保存目录为项目中的 static/avatar
        String saveDir = System.getProperty("user.dir") + "/src/main/resources/static/avatar";
        downloadImagesFromUrl(url, saveDir);
    }

    public static void downloadImagesFromUrl(String url, String saveDir) {
        try {
            // 创建保存目录
            File dir = new File(saveDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 使用 Jsoup 连接到网页并获取文档
            Document doc = Jsoup.connect(url).get();
            // 选择所有 img 标签
            Elements imgElements = doc.select("img");

            for (Element img : imgElements) {
                String imgUrl = img.absUrl("src");
                if (!imgUrl.isEmpty()) {
                    downloadImage(imgUrl, saveDir);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void downloadImage(String imgUrl, String saveDir) {
        try {
            // 创建 URL 对象
            URL url = new URL(imgUrl);
            // 打开 HTTP 连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            // 获取输入流
            InputStream in = conn.getInputStream();
            // 生成图片文件名
            String fileName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1);
            File outputFile = new File(saveDir, fileName);

            // 创建输出流
            OutputStream out = new FileOutputStream(outputFile);

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }

            // 关闭流
            in.close();
            out.close();
            System.out.println("下载完成: " + imgUrl);
        } catch (IOException e) {
            System.err.println("下载失败: " + imgUrl + " - " + e.getMessage());
        }
    }
}